<template>
  <scroll-view class="account-info" :style="{ height: screenHeight }">
    <div class="wrap">
      <div class="info-block">
        <div class="te">
          <div class="button" @click="toUserInfo">{{ userInfo.name }} &#62;</div>
        </div>
        <div class="te">积分 Redeem Points {{ userInfo.integral }}</div>
        <div class="te">
          <div class="button" @click="toMessage">
            <div class="span">我的消息 My Messages</div>
            <div class="red" v-if="hadUnread"></div>
            <div class="span">></div>
          </div>
        </div>
      </div>
      <div class="vip-box">
        <div class="not-vip" v-if="!isVip">
          <div class="not-text" @click="toVipInfo">
            <div class="span">立即订阅会员，享受更多优惠。</div>
            <div class="span">Subscribe to our membership for special offers.</div>
          </div>

          <div class="not-img">
            <img class="img" src="@/static/icon/not-vip.png" mode="aspectFill" alt="" />
          </div>
        </div>
        <div class="not-vip" v-else>
          <div class="not-text">
            <div class="span">会员二维码</div>
            <div class="span">Membership QR code</div>
          </div>
          <div class="vip-img">
            <!-- 调试信息 -->
            <div class="code-canvas" :class="{ active: currentQRCodeIndex === 0 }">
              <uv-qrcode
                ref="qrcode1"
                size="200px"
                :auto="true"
                :loading="false"
                :value="qrCodeValues[0]"
                @complete="(result) => onQRCodeComplete(result, 0)"
              ></uv-qrcode>
            </div>
            <div class="code-canvas" :class="{ active: currentQRCodeIndex === 1 }">
              <uv-qrcode
                ref="qrcode2"
                size="200px"
                :auto="true"
                :loading="false"
                :value="qrCodeValues[1]"
                @complete="(result) => onQRCodeComplete(result, 1)"
              ></uv-qrcode>
            </div>
          </div>
          <div class="not-text">
            <!-- &#62; 是 > 右箭头代码 -->
            <div class="span" @click="toVipInfo">会员详情 Membership Information &#62;</div>
          </div>
        </div>
      </div>
    </div>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, onUnmounted, watch, computed, defineExpose, nextTick } from 'vue'
import { useStore } from 'vuex'
import { messageUnreadCount } from '@/utils/api/message'
const store = useStore()
import { getQrCode } from '@/utils/api/user'
const screenHeight = ref<number>(0)
const statusBarHeight = computed(() => store.getters['system/statusBarHeight'])
const bottomSafeArea = computed(() => store.getters['system/bottomSafeArea'])
screenHeight.value = `calc(100vh - ${statusBarHeight.value}px - ${bottomSafeArea.value}px - 90rpx - 116rpx - 126rpx)`
const userInfo = computed(() => store.state.user.userInfo)
import { encryptDes } from '@/utils/encryption'
let isVip = computed(() => {
  return store.getters['user/isVip']
})
const qrcode1 = ref()
const qrcode2 = ref()
const toVipInfo = () => {
  uni.navigateTo({
    url: '/pages/vipInfo/vipInfo'
  })
}

let hadUnread = ref<boolean>(false)
const getUnReadCount = async () => {
  const { code, data } = await messageUnreadCount()
  if (code === 200) {
    hadUnread.value = data > 0
  }
}

const toMessage = () => {
  uni.navigateTo({
    url: '/pages/message/message'
  })
}
const toUserInfo = () => {
  uni.navigateTo({
    url: '/pages/userInfo/userInfo'
  })
}
// 个人的code
let userCode: number | string = ''
let codeValue = ref<string>('test123')
let isQRCodeReady = ref<boolean>(false)
let currentQRCodeIndex = ref<number>(0)
let qrCodeValues = ref<string[]>(['test123', 'test123'])

/*
 * userCode :个人的code,通过请求获取
 * id :用户的id，通过请求获取
 * codeValue :二维码的值
 */
const createCode = () => {
  // id 也得是字符串，不能是数字
  let id = store.state.user.userInfo.id + ''
  let clientUser = `clientUser^${encryptDes(id)}`
  let code = encryptDes(String(userCode))
  console.log('clientUser', clientUser)
  console.log('code', code)

  // 生成新的二维码内容
  const newQRCodeValue = `clientUser^${encryptDes(id)}^code^${encryptDes(String(userCode))}`
  console.log('新二维码内容:', newQRCodeValue)

  // 更新非当前显示的二维码内容
  const nextIndex = currentQRCodeIndex.value === 0 ? 1 : 0
  qrCodeValues.value[nextIndex] = newQRCodeValue

  // 等待一小段时间后切换显示，确保新二维码已经生成
  setTimeout(() => {
    currentQRCodeIndex.value = nextIndex
    isQRCodeReady.value = false
    console.log('切换到二维码索引:', nextIndex)
  }, 400)
}

const haveCode = async () => {
  // 清不掉定时器----
  if (uni.getStorageSync('currentTopTab') === 0) {
    console.log('开始获取二维码数据...')
    const { code, data } = await getQrCode()
    console.log('二维码API返回:', { code, data })
    if (code !== 200) {
      console.log('二维码API返回错误码:', code)
      return
    }
    userCode = data
    console.log('设置userCode:', userCode)
    createCode()
  } else {
    clearInterval(timeCode.value)
    timeCode.value = null
  }
}

// 设置定时器
let timeCode = ref<any>(null)

const initQRCode = () => {
  // 初始化两个二维码组件
  qrCodeValues.value = ['test123', 'test123']
  currentQRCodeIndex.value = 0
  isQRCodeReady.value = false
  console.log('初始化二维码组件')
}

const initData = () => {
  store.dispatch('user/getUserInfo')
  // 初始化二维码组件
  initQRCode()
  // 进来的时候先获取个人code
  haveCode()
  // 获取未读消息数量
  getUnReadCount()
  // 这里是看看timeCode 是否为空，为空就执行定时器，不为空就不执行
  if (!timeCode.value) {
    timeCode.value = setInterval(() => {
      haveCode()
    }, 5000)
  }
}
const closeCode = () => {}

const onQRCodeComplete = (result: any, index?: number) => {
  console.log('二维码生成完成:', result, '索引:', index)
  if (result.success) {
    console.log('二维码生成成功')
    isQRCodeReady.value = true
  } else {
    console.log('二维码生成失败:', result.errMsg)
    isQRCodeReady.value = false
  }
}

defineExpose({
  initData,
  closeCode
})
// onShow(() => {
//   getInfo()
// })
</script>

<style lang="scss" scoped>
@import './accountInfo.scss';
</style>
